##################################################################################################################################
#
# Copyright (C) 2008-2012 Mind System Connection. Lda. Part of Daidze Software, created by Siqsuruq. All other rights reserved.
#
# Mind System Connection Webpage: www.msysc.org
# Daidze Software Page: www.daidze.com www.daidze.org
# E-mail: admin@msysc.org, siqsuruq@gmail.com
#
##################################################################################################################################

############################## Process XML Form #######################
# proc get_v {table} {
# 	set data [dict create]
# 	foreach key [dict keys $::form::fdata] value [dict values $::form::fdata] {
# 		if {[string match -nocase *.ebin $value] == 1} {
# 			if {[$value get] == ""} {
# 			} else {
# 			set w_img [image create photo -file  [$value get]]
# 			set new_w 400
# 			set w [image width $w_img]
# 
# 				set pr [expr {$w/400}]
# 				set new_h [expr {[image height $w_img]/$pr}]
# 
# 			set scaled_img [resize $w_img $new_w $new_h]
# 			$scaled_img write [file join res modul tmp tempimg]
# 
# 			set fbin [open "[file join res modul tmp tempimg]" "r"]
# 			fconfigure $fbin -translation binary
# 
# 			set content [read $fbin]
# 			dict set data $key $content
# 			close $fbin
# 			}
# 		} else { dict set data $key [$value get] }
# 	}
# # puts $data
# # 	$::db insert_all $table $data
# }

proc view_img {tablelist table} {

	set row [$tablelist rowcget [$tablelist curselection] -text]
	switch $table {
		reason { set indx [lindex $row 0] }
		client_place { 
			set indx [$::db select_id_by_name reason [lindex $row 9]]
		}
	}

	set query "SELECT bin_foto FROM reason WHERE id='$indx'"
	set img [lindex [lindex  [$::db execute_query $query] 0] 0]

	if {$img != ""} {
		set fbin [open "[file join res modul tmp tempimgfromdb]" "w+"]
		fconfigure $fbin -translation binary
		puts $fbin [pg_unescape_bytea $img]
		close $fbin
		set tmp_img [image create photo -file [file join res modul tmp tempimgfromdb]]
	} else {
		set tmp_img [image create photo -file [file join $::img no_img.png]]
	}
	img_viewer $tmp_img
}

proc img_viewer {img} {
	set viewer .viewer
	catch {destroy $viewer}
	toplevel $viewer
	wm title $viewer [::msgcat::mc "Image viewer"]
	pack [label $viewer.picture -borderwidth 2 -relief sunken -image $img]
}

proc update_v {table} {
	set data [dict create]
	foreach key [dict keys $::form::fdata] value [dict values $::form::fdata] {
		if {[string match fk_* $key] == 1} {
			set fktable [string trim $key fk_]
			dict set data $key [$::db select_id_by_name $fktable [$value get]]
		} else {
			dict set data $key [$value get]
		}
	}
	$::db update_all $table $data
}




# proc clear_v {} {
# 	set values [dict values $::form::fdata]
# 	for {set i 0} {$i < [llength $values]} {incr i} {
# 		[lindex $values $i] delete 0 end
# 	}
# }

############################## Table ##############################
proc make_table {fr headers result} {
	set cont [frame $fr.cont]
	pack $cont -fill both -expand 0

	tablelist::tablelist $cont.tbl -columntitles $headers -labelcommand tablelist::sortByColumn \
	      -height 10 -width 90 -stretch all -yscrollcommand [list $cont.vsb set] -xscrollcommand [list $cont.tbl.hsb set]

	set num_result [pg_result $result -numTuples]
	for {set i 0} {$i < $num_result} {incr i} {
		$cont.tbl insert end [pg_result $result -getTuple $i]
		$cont.tbl cellconfigure end,1 -foreground grey50 -selectforeground blue
	}
	pack $cont.tbl -expand 1 -fill x -side left
	ttk::scrollbar $cont.vsb -orient vertical -command [list $cont.tbl yview]
	ttk::scrollbar $cont.tbl.hsb -orient horizontal -command [list $cont.tbl xview]
	pack $cont.vsb -fill both -side right
	pack $cont.tbl.hsb -fill x
}









proc new_file {filename} {
	set dir [file join res modul tmp]
	set new_file [open $dir/$filename w+]
	return $new_file
}

proc resize {src newx newy {dest ""} } {

     set mx [image width $src]
     set my [image height $src]

     if { "$dest" eq ""} {
         set dest [image create photo]
     }
     $dest configure -width $newx -height $newy

     # Check if we can just zoom using -zoom option on copy
     if { $newx % $mx == 0 && $newy % $my == 0} {

         set ix [expr {$newx / $mx}]
         set iy [expr {$newy / $my}]
         $dest copy $src -zoom $ix $iy
         return $dest
     }

     set ny 0
     set ytot $my

     for {set y 0} {$y < $my} {incr y} {

         #
         # Do horizontal resize
         #

         foreach {pr pg pb} [$src get 0 $y] {break}

         set row [list]
         set thisrow [list]

         set nx 0
         set xtot $mx

         for {set x 1} {$x < $mx} {incr x} {

             # Add whole pixels as necessary
             while { $xtot <= $newx } {
                 lappend row [format "#%02x%02x%02x" $pr $pg $pb]
                 lappend thisrow $pr $pg $pb
                 incr xtot $mx
                 incr nx
             }

             # Now add mixed pixels

             foreach {r g b} [$src get $x $y] {break}

             # Calculate ratios to use

             set xtot [expr {$xtot - $newx}]
             set rn $xtot
             set rp [expr {$mx - $xtot}]

             # This section covers shrinking an image where
             # more than 1 source pixel may be required to
             # define the destination pixel

             set xr 0
             set xg 0
             set xb 0

             while { $xtot > $newx } {
                 incr xr $r
                 incr xg $g
                 incr xb $b

                 set xtot [expr {$xtot - $newx}]
                 incr x
                 foreach {r g b} [$src get $x $y] {break}
             }

             # Work out the new pixel colours

             set tr [expr {int( ($rn*$r + $xr + $rp*$pr) / $mx)}]
             set tg [expr {int( ($rn*$g + $xg + $rp*$pg) / $mx)}]
             set tb [expr {int( ($rn*$b + $xb + $rp*$pb) / $mx)}]

             if {$tr > 255} {set tr 255}
             if {$tg > 255} {set tg 255}
             if {$tb > 255} {set tb 255}

             # Output the pixel

             lappend row [format "#%02x%02x%02x" $tr $tg $tb]
             lappend thisrow $tr $tg $tb
             incr xtot $mx
             incr nx

             set pr $r
             set pg $g
             set pb $b
         }

         # Finish off pixels on this row
         while { $nx < $newx } {
             lappend row [format "#%02x%02x%02x" $r $g $b]
             lappend thisrow $r $g $b
             incr nx
         }

         #
         # Do vertical resize
         #

         if {[info exists prevrow]} {

             set nrow [list]

             # Add whole lines as necessary
             while { $ytot <= $newy } {

                 $dest put -to 0 $ny [list $prow]

                 incr ytot $my
                 incr ny
             }

             # Now add mixed line
             # Calculate ratios to use

             set ytot [expr {$ytot - $newy}]
             set rn $ytot
             set rp [expr {$my - $rn}]

             # This section covers shrinking an image
             # where a single pixel is made from more than
             # 2 others.  Actually we cheat and just remove
             # a line of pixels which is not as good as it should be

             while { $ytot > $newy } {

                 set ytot [expr {$ytot - $newy}]
                 incr y
                 continue
             }

             # Calculate new row

             foreach {pr pg pb} $prevrow {r g b} $thisrow {

                 set tr [expr {int( ($rn*$r + $rp*$pr) / $my)}]
                 set tg [expr {int( ($rn*$g + $rp*$pg) / $my)}]
                 set tb [expr {int( ($rn*$b + $rp*$pb) / $my)}]

                 lappend nrow [format "#%02x%02x%02x" $tr $tg $tb]
             }

             $dest put -to 0 $ny [list $nrow]

             incr ytot $my
             incr ny
         }

         set prevrow $thisrow
         set prow $row

         update idletasks
     }

     # Finish off last rows
     while { $ny < $newy } {
         $dest put -to 0 $ny [list $row]
         incr ny
     }
     update idletasks

     return $dest
 }






